package org.example.domain.strategy.service.rule.chain.factory;

import lombok.*;
import org.example.domain.strategy.model.entity.StrategyEntity;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.rule.chain.ILogicChain;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class DefaultChainFactory {
    private final Map<String, ILogicChain> logicChainGroup;

    private IStrategyRepository repository;

    public DefaultChainFactory(Map<String, ILogicChain> logicChainGroup,IStrategyRepository repository){
        this.logicChainGroup=logicChainGroup;
        this.repository=repository;
    }

    public ILogicChain openLogicChain(Long strategyId){
        StrategyEntity strategy=repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategy.ruleModels();

        //如果不存在责任链，则走兜底节点
        if (null==ruleModels||ruleModels.length==0){
            return logicChainGroup.get(LogicModel.RULE_DEFAULT.getCode());
        }
        // 获得责任链起始节点
        ILogicChain logicChain=logicChainGroup.get(ruleModels[0]);
        // 拼接节点
        ILogicChain current=logicChain;
        for(int i=1;i<ruleModels.length;i++){
            ILogicChain nextChain = logicChainGroup.get(ruleModels[i]);
            current=current.appendNext(nextChain);
        }
        // 最后拼接兜底节点
        current.appendNext(logicChainGroup.get(LogicModel.RULE_DEFAULT.getCode()));
        return logicChain;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /** 抽奖奖品ID - 内部流转使用 */
        private Integer awardId;
        /**  */
        private String logicModel;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }

}
